package com.xunwulian.web.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.xunwulian.base.exception.PayException;
import com.xunwulian.base.param.WeixinParam;
import com.xunwulian.base.util.*;
import com.xunwulian.base.util.StringUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码工具
 */
public class QRUtil {
    // 黑白两色
    private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;

    private com.xunwulian.base.util.FileUtil fileUtil = new com.xunwulian.base.util.FileUtil();

    private BeanUtil beanUtil = new BeanUtil();

    private MyLogUtil myLogUtil = new MyLogUtil(QRUtil.class);

    /**
     * 获取微信支付的二维码
     *
     * @param paramMap 请求微信二维码时请求的数据的map格式
     * @return 获取到的二维码
     * @throws PayException
     */
    public String requestCodeUrl(Map<String, String> paramMap) throws PayException {
        PostUtil postUtil = new PostUtil();

        // 把参数转换成XML数据格式
        String xmlData = StringUtil.mapToXml(paramMap);

        // 请求数据打印
        myLogUtil.log("***********请求参数***********");
        beanUtil.log(xmlData);

        String resXml = postUtil.postData(WeixinParam.PAY_URL, xmlData);
        if (resXml == null) {
            throw new PayException("postData 时出现异常...");
        }

        // 响应数据打印
        myLogUtil.log("***********响应数据***********");
        beanUtil.log(resXml);

        String code_url = parseCodeUrlByXml(resXml);

        // 二维码打印
        myLogUtil.log("***********响应的二维码***********");
        myLogUtil.log(code_url);

        return code_url;
    }

    /**
     * 从响应的XML中提取微信的二维码
     *
     * @param resXml 响应的xml数据
     * @return 提取的二维码内容
     */
    private String parseCodeUrlByXml(String resXml) {
        Document document;
        String code_url = null;

        try {
            document = DocumentHelper.parseText(resXml);
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }

        if (document != null) {
            Element root = document.getRootElement();
            if (root == null) {
                return null;
            }
            Element codeUrl = root.element("code_url");
            if (codeUrl == null) {
                return null;
            }
            code_url = codeUrl.getText(); // 解析 xml 获得 code_url
        }
        return code_url;
    }

    /**
     * 生成二维码图片到本地
     *
     * @param content 包含二维码信息的字串
     * @param path    存储的目录
     * @return 存储的路径
     * @throws PayException 描述支付信息的异常
     */
    public String generateQR(String content, String path) throws PayException {
        if (content == null) {
            return null;
        }

        path = path == null ? "./" : path;

        String fileName = generateFileName(content.getBytes()) + ".png";

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map<EncodeHintType, String> hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, WeixinParam.CHAR_SET); // 设置字符集编码类型

        BitMatrix bitMatrix;
        try {
            bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE,
                    300, 300, hints);

            // 创建存储图片的文件
            File file = new File(path, fileName);

            try {
                // 存储二维码图片
                writeToFile(bitMatrix, "png", file);

                return file.getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 生成二维码到字节数组
     *
     * @param content 包含二维码信息的字串
     * @return 二维码图片的字节数组
     */
    public byte[] generateQR(String content) {
        if (content == null) {
            return null;
        }

        byte[] qrcode = null;

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map<EncodeHintType, String> hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, WeixinParam.CHAR_SET); // 设置字符集编码类型
        BitMatrix bitMatrix;

        try {
            bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);

            BufferedImage image = writeToImage(bitMatrix);
            // 返回二维码字节数组
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos);
                qrcode = baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                fileUtil.closeIO(baos);
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }

        return qrcode;
    }

    /**
     * 对二维码内容进行MD5加密，将加密后的内容作为文件名
     *
     * @param content 二维码的内容字串
     * @return 加密后的字串
     */
    private String generateFileName(byte[] content) {
        return MD5Util.MD5Encode(new String(content), WeixinParam.CHAR_SET);
    }

    /**
     * 将点阵写到文件中
     *
     * @param matrix 点阵
     * @param format 文件格式，例如jpg、png等
     * @param file   要写入的文件
     * @throws IOException
     */
    private void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = writeToImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    /**
     * 将二维码的点阵写到BufferedImage里面
     *
     * @param matrix 二维码的点阵
     * @return 存储二维码信息的BufferedImage
     */
    private BufferedImage writeToImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }

        return image;
    }
}
